package com.yanqu.road.server.gameplayer.module.activity.lottery;

import com.yanqu.road.dao.impl.activity.lottery.UserActivityLotteryDataDaoImpl;
import com.yanqu.road.dao.impl.activity.lottery.UserActivityLotteryGuaranteeDataDaoImpl;
import com.yanqu.road.entity.activity.args.ConditionTypeValueArgs;
import com.yanqu.road.entity.activity.lottery.*;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.LogActivityLotteryDraw;
import com.yanqu.road.entity.log.LogActivityLotteryDrawEx;
import com.yanqu.road.pb.activity.ActivityLotteryProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.lottery.ActivityLotteryMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ActivityLotteryModule extends GeneralModule {

    private Map<Integer, UserActivityLotteryData> userDataMap = new ConcurrentHashMap<>();

    private Map<Integer,UserActivityLotteryGuaranteeData> guaranteeDataMap = new ConcurrentHashMap<>();

    public ActivityLotteryModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        guaranteeDataMap = new UserActivityLotteryGuaranteeDataDaoImpl().getUserActivityLotteryGuaranteeDataMap(player.getUserId());
        List<Integer> activityIdList = new ArrayList<>();
        for (Map.Entry<Integer, Map<Integer,ActivityLotteryConfig>> entry : ActivityLotteryMgr.getConfigMap().entrySet()) {
            ActivityLotteryConfig config = entry.getValue().get(0);
            if(ActivityMgr.activityInShowTime(config.getActivityInfo())){
                activityIdList.add(config.getActivityInfo().getActivityId());
            }
        }
        if(activityIdList.size() > 0){
            userDataMap = new UserActivityLotteryDataDaoImpl().getUserActivityLotteryData(activityIdList, player.getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        for (UserActivityLotteryGuaranteeData guaranteeData:guaranteeDataMap.values()){
            if (guaranteeData.isInsertOption()) {
                new UserActivityLotteryGuaranteeDataDaoImpl().add(guaranteeData);
            } else if (guaranteeData.isUpdateOption()) {
                new UserActivityLotteryGuaranteeDataDaoImpl().update(guaranteeData);
            }
        }

        for (Map.Entry<Integer, UserActivityLotteryData> entry : userDataMap.entrySet()) {
            UserActivityLotteryData data = entry.getValue();
            if(data.isInsertOption()){
                new UserActivityLotteryDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new UserActivityLotteryDataDaoImpl().update(data);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {

        syncConfig();
        initUserData();
        syncUserData();
    }

    /**
     * 获取某种类型的抽奖次数
     */
    public UserActivityLotteryGuaranteeData getOrCreateGuaranteeTypeData(int type,UserActivityLotteryData userData) {
        if (type <= 0){
//            log.error("skin Lottery activity getDrawCount type error,type = {}",type);
            return null;
        }
        //无双美女不走跨活动保底
        if (type == eActivityType.PeerlessBeautyLotteryActivity.getValue()){
            return null;
        }
        if (guaranteeDataMap == null) {
            guaranteeDataMap = new ConcurrentHashMap<>();
        }
        if (!guaranteeDataMap.containsKey(type)) {
            guaranteeDataMap.put(type,new UserActivityLotteryGuaranteeData(player.getUserId(),type,userData.getTotalDrawTimes(),userData.getGetItemMap()));
        }

        return guaranteeDataMap.get(type);
    }


    /**
     * 增加某类型抽奖次数
     */
    public void addDrawCount(UserActivityLotteryData userData,int type, int drawCount) {
        if (drawCount <= 0) {
//            log.error("skin Lottery activity addDrawCount drawCount error,drawCount = {}",drawCount);
            return;
        }
        if (type <= 0){
//            log.error("skin Lottery activity addDrawCount type error,type = {}",type);
            return;
        }
        if (type == eActivityType.PeerlessBeautyLotteryActivity.getValue()){
            return;
        }
        UserActivityLotteryGuaranteeData guaranteeTypeData = getOrCreateGuaranteeTypeData(type, userData);
        if (guaranteeTypeData == null){
            log.error("skin Lottery activity addDrawCount guaranteeTypeData is null,userId = {},type = {}",userData.getUserId(),type);
            return;
        }
        guaranteeTypeData.setDrawCount(guaranteeTypeData.getDrawCount() + drawCount);
        guaranteeTypeData.setGetItemMap(new ConcurrentHashMap<>(userData.getGetItemMap()));

    }

    /**
     * 检测是否完成类型保底 重新开始
     */
    public void checkNeedResetDrawCount(UserActivityLotteryData userData, ActivityLotteryConfig config) {
        if (config.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue()){
            return;
        }

        if (config.getActivityType() == 0){
            return;
        }

        if (guaranteeDataMap == null) {
            guaranteeDataMap = new ConcurrentHashMap<>();
        }
        UserActivityLotteryGuaranteeData guaranteeTypeData = getOrCreateGuaranteeTypeData(config.getActivityType(), userData);
        if (guaranteeTypeData == null) {
            return;
        }

        //如果获得的已经超过或等于配置
        if (userData.getGetItemMap().size() >= config.getLotteryInfoList().size()){
            //重置活动信息
            userData.setGetItemMap(new ConcurrentHashMap<>());
            //重置跨活动信息 已经抽到的
            guaranteeTypeData.setGetItemMap(new ConcurrentHashMap<>());
            //重置总抽奖次数
            guaranteeTypeData.setDrawCount(0);
        }
    }



    /**
     * 获取玩家数据
     */
    public UserActivityLotteryData getUserData(int activityId) {
        return userDataMap.get(activityId);
    }

    public int drawBox(int activityId, int drawCount) {
        UserActivityLotteryData userData = getUserData(activityId);
        if (userData == null) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        ActivityLotteryConfig config = ActivityLotteryMgr.getActivityLotteryConfig(activityId,userData.getLotteryType());
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        Property cost = new Property();
        if (drawCount == 1) {
            cost = PropertyHelper.parseStringToProperty(config.getCost());
        } else {
            cost = PropertyHelper.parseStringToProperty(config.getTenCost());
        }

        Random random = new Random();
        boolean isNeedCross = false;
        List<ActivityLotteryResult> resultList = new ArrayList<>();
        ActivityLotteryProto.CrossActivityLotteryDrawReqMsg.Builder crossReqMsg = ActivityLotteryProto.CrossActivityLotteryDrawReqMsg.newBuilder();
        crossReqMsg.setActivityId(activityId);
        UserActivityLotteryGuaranteeData guaranteeTypeData = getOrCreateGuaranteeTypeData(config.getActivityType(), userData);
        for (int i = 0; i < drawCount; i++) {
            ActivityLotteryResult result = ActivityLotteryMgr.draw(userData, config, random,guaranteeTypeData);
            if (result.getRet() != 0) {
                return result.getRet();
            }
            resultList.add(result);
            if (result.getLotteryInfo() == null) {
                isNeedCross = true;
                crossReqMsg.addDrawIsHide(1);
            } else {
                crossReqMsg.addDrawIsHide(0);
            }
        }
        if (isNeedCross) {
            //预扣
            player.getModule(PreReduceModule.class).preReduce(cost);
            player.sendPacket(CrossProtocol.C_ACTIVITY_LOTTERY_DRAW_HIDE_BOX_EX, crossReqMsg);
        } else {
            // 扣消耗
            if (!player.getModule(CurrencyModule.class).removeCurrency(cost,
                    eLogMoneyType.ActivityLottery, eLogMoneyType.ActivityLotteryDrawCost, userData.getActivityId() + "")) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            if (config.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue()) {
                for (Map.Entry<Integer, BigInteger> goodsAndCount : cost.getGoods().entrySet()) {
                    int goodsId= goodsAndCount.getKey();
                    BigInteger count = goodsAndCount.getValue();
                    GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
                    int rankScoreAdd = goodsInfo.getParamList().get(0).multiply(count).intValue();
                    player.notifyListener(eGamePlayerEventType.PeerlessBeautyLotteryRank.getValue(), new ConditionTypeValueArgs(activityId, rankScoreAdd));
                    break;
                }
            }
            //直接拿奖励
            synchronized (userData) {
                Property reward = new Property();
                String rewardString = "";
                for (ActivityLotteryResult result : resultList) {
                    ActivityLotteryInfo item = ActivityLotteryMgr.normalDraw(userData, config, random, result.isExcludeHide(),guaranteeTypeData);
                    Property handleReward = handleDrawResult(userData, config, item);
                    reward.addProperty(handleReward);
                    rewardString += PropertyHelper.parsePropertyToString(handleReward) + ";";
                }

                ActivityLotteryProto.ActivityLotteryDrawRespMsg.Builder respMsg = ActivityLotteryProto.ActivityLotteryDrawRespMsg.newBuilder();
                respMsg.setRet(0);
                respMsg.setActivityId(userData.getActivityId());
                respMsg.setReward(rewardString);
                player.sendPacket(Protocol.U_ACTIVITY_LOTTERY_DRAW, respMsg);

                //抽奖日志
                LogActivityLotteryDrawEx drawLog = new LogActivityLotteryDrawEx(player.getUserId(), userData.getActivityId(), drawCount, rewardString, userData.getLotteryType());
                AutoLogMgr.add(drawLog);
            }
            syncUserData();
        }
        return 0;
    }

    /**
     * 前6次必须共享跨服的大奖，不然就是普通奖励
     */
    public int drawBoxFromCross(int activityId, boolean canHide) {
        UserActivityLotteryData userData = getUserData(activityId);
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        ActivityLotteryConfig config = ActivityLotteryMgr.getActivityLotteryConfig(activityId,userData.getLotteryType());
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        // 返还预扣除
        player.getModule(PreReduceModule.class).restorePreReduce(config.getCost());

        Random random = new Random();

        synchronized (userData) {
            ActivityLotteryInfo item;
            if (canHide) {
                item = ActivityLotteryMgr.getHideItem(config, random);
            } else {
                UserActivityLotteryGuaranteeData guaranteeTypeData = getOrCreateGuaranteeTypeData(config.getActivityType(), userData);
                item = ActivityLotteryMgr.normalDraw(userData, config, random, true,guaranteeTypeData);
            }
            // 扣消耗
            if (!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(config.getCost()),
                    eLogMoneyType.ActivityLottery, eLogMoneyType.ActivityLotteryDrawCost, userData.getActivityId() + "")) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            Property reward = handleDrawResult(userData, config, item);
            if (canHide) {
                //中过大奖
                userData.setGetSharedBox(true);
            }
            ActivityLotteryProto.ActivityLotteryDrawRespMsg.Builder respMsg = ActivityLotteryProto.ActivityLotteryDrawRespMsg.newBuilder();
            respMsg.setRet(0);
            respMsg.setActivityId(userData.getActivityId());
            respMsg.setReward(PropertyHelper.parsePropertyToString(reward));
            player.sendPacket(Protocol.U_ACTIVITY_LOTTERY_DRAW, respMsg);
            return 0;
        }
    }

    /**
     * 跨服返回抽奖
     */
    public int drawBoxFromCross(int activityId, List<Integer> drawIsHide) {
        UserActivityLotteryData userData = getUserData(activityId);
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        ActivityLotteryConfig config = ActivityLotteryMgr.getActivityLotteryConfig(activityId,userData.getLotteryType());
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        Property cost = new Property();
        if (drawIsHide.size() == 1) {
            cost = PropertyHelper.parseStringToProperty(config.getCost());
        } else {
            cost = PropertyHelper.parseStringToProperty(config.getTenCost());
        }
        // 返还预扣除
        player.getModule(PreReduceModule.class).restorePreReduce(cost);
        // 扣消耗
        if (!player.getModule(CurrencyModule.class).removeCurrency(cost,
                eLogMoneyType.ActivityLottery, eLogMoneyType.ActivityLotteryDrawCost, userData.getActivityId() + "")) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        if (config.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue()) {
            for (Map.Entry<Integer, BigInteger> goodsAndCount : cost.getGoods().entrySet()) {
                int goodsId= goodsAndCount.getKey();
                BigInteger count = goodsAndCount.getValue();
                GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
                int rankScoreAdd = goodsInfo.getParamList().get(0).multiply(count).intValue();
                player.notifyListener(eGamePlayerEventType.PeerlessBeautyLotteryRank.getValue(), new ConditionTypeValueArgs(activityId, rankScoreAdd));
                break;
            }
        }
        Random random = new Random();
        Property reward = new Property();
        String rewardString = "";
        synchronized (userData) {
            for (Integer isHide : drawIsHide) {
                ActivityLotteryInfo item;
                if (isHide == 1) {
                    item = ActivityLotteryMgr.getHideItem(config, random);
                    //中过大奖
                    userData.setGetSharedBox(true);
                } else {
                    UserActivityLotteryGuaranteeData guaranteeTypeData = getOrCreateGuaranteeTypeData(config.getActivityType(), userData);
                    item = ActivityLotteryMgr.normalDraw(userData, config, random, true,guaranteeTypeData);
                }
                Property handleReward = handleDrawResult(userData, config, item);
                reward.addProperty(handleReward);
                rewardString += PropertyHelper.parsePropertyToString(handleReward) + ";";
            }
        }

        ActivityLotteryProto.ActivityLotteryDrawRespMsg.Builder respMsg = ActivityLotteryProto.ActivityLotteryDrawRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(userData.getActivityId());
        respMsg.setReward(rewardString);
        player.sendPacket(Protocol.U_ACTIVITY_LOTTERY_DRAW, respMsg);
        syncUserData();

        //抽奖日志
        LogActivityLotteryDrawEx drawLog = new LogActivityLotteryDrawEx(player.getUserId(), userData.getActivityId(), drawIsHide.size(), rewardString, userData.getLotteryType());
        AutoLogMgr.add(drawLog);
        return 0;
    }

    /**
     * 处理盲合奖励
     */
    public Property handleDrawResult(UserActivityLotteryData userData, ActivityLotteryConfig config, ActivityLotteryInfo item) {
        if (item.getIsHide() == 1) {
            //重置未抽中隐藏款次数
            userData.setCommonDrawTimes(0);
            if (userData.getTotalDrawTimes() < config.getShareNTimes()) {
                userData.setGetSharedBox(true);
            }
        } else {
            //未抽中隐藏款次数+1
            userData.setCommonDrawTimes(1 + userData.getCommonDrawTimes());
        }

        // 加奖励
        Property reward = PropertyHelper.parseStringToProperty(item.getRewards());
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.ActivityLottery, eLogMoneyType.ActivityLotteryDrawGet);

        userData.setTotalDrawTimes(1 + userData.getTotalDrawTimes());
        userData.addGetItem(item.getId(), 1);
        userData.setLastDrawItem(item.getId());

        addDrawCount(userData,config.getActivityType(),1);        //跨活动用的
        checkNeedResetDrawCount(userData,config);                           //检测是否需要重置保底

        if (item.getIsNotice() == 1) {
            // 上公告
            ActivityLotteryProto.CrossActivityLotteryUploadNoticeReqMsg.Builder noticeBuilder = ActivityLotteryProto.CrossActivityLotteryUploadNoticeReqMsg.newBuilder();
            noticeBuilder.setActivityId(config.getActivityInfo().getActivityId());
            noticeBuilder.setPlayer(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
            noticeBuilder.setGoodsId(item.getRewards());
            noticeBuilder.setType(item.getIsHide()); // 1隐藏款，0普通
            noticeBuilder.setTime(System.currentTimeMillis());
            player.sendPacket(Protocol.C_ACTIVITY_LOTTERY_UPLOAD_NOTICE, noticeBuilder);
        }

        //抽奖日志
        LogActivityLotteryDraw drawLog = new LogActivityLotteryDraw(player.getUserId(), userData.getActivityId(), item.getId());
        AutoLogMgr.add(drawLog);

//        ActivityLotteryProto.ActivityLotteryDrawRespMsg.Builder respMsg = ActivityLotteryProto.ActivityLotteryDrawRespMsg.newBuilder();
//        respMsg.setRet(0);
//        respMsg.setActivityId(userData.getActivityId());
//        respMsg.setReward(reward);
//        player.sendChannelPacket(Protocol.U_ACTIVITY_LOTTERY_DRAW, respMsg);
        return reward;
    }

    public void syncConfig() {

        ActivityLotteryProto.ActivityLotteryConfigSyncMsg.Builder syncMsg = ActivityLotteryProto.ActivityLotteryConfigSyncMsg.newBuilder();
        for (Map.Entry<Integer, Map<Integer,ActivityLotteryConfig>> entry : ActivityLotteryMgr.getConfigMap().entrySet()) {
            ActivityLotteryConfig config = entry.getValue().get(0);
            if(ActivityMgr.activityOverTime(config.getActivityInfo())){
                continue;
            }
            if (config.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue()) {
                if (!SystemOpenMgr.systemOpen(player, eSystemId.PeerlessBeautyLottery.getValue())) {
                    continue;
                }
            }
            ActivityLotteryProto.ActivityLotteryItemConfigListTemp.Builder listTemp = ActivityLotteryProto.ActivityLotteryItemConfigListTemp.newBuilder();
            listTemp.setActivityId(config.getActivityInfo().getActivityId());
            for (ActivityLotteryInfo info : config.getLotteryInfoList()) {
                ActivityLotteryProto.ActivityLotteryItemConfigTemp.Builder builder = ActivityLotteryProto.ActivityLotteryItemConfigTemp.newBuilder();
                builder.setId(info.getId());
                builder.setName(ServerLanguageMgr.getContent(info.getName(), player.getLanguage()));
                builder.setShowWeights(info.getShowWeights());
                builder.setRewards(info.getRewards());
                builder.setSort(info.getSort());
                builder.setIsHide(info.getIsHide());
                builder.setLotteryType(info.getLotteryType());
                listTemp.addItem(builder);
            }
            List<ActivityLotteryParamInfo> tempList = new ArrayList<>();
            if(null != config.getLotteryParamInfoMap()){
                tempList.addAll(config.getLotteryParamInfoMap().values());
                tempList.sort(Comparator.comparingInt(ActivityLotteryParamInfo::getId));
            }
            for(ActivityLotteryParamInfo paramInfo : tempList){
                ActivityLotteryProto.ActivityLotteryParamConfigTemp.Builder builder = ActivityLotteryProto.ActivityLotteryParamConfigTemp.newBuilder();
                builder.setId(paramInfo.getId());
                builder.setSkinExtractLuckyParam(paramInfo.getSkinExtractLuckyParam());
                builder.setSkinExtractAddParam(paramInfo.getSkinExtractAddParam());
                builder.setSkinExtractRewardRepeatControl(paramInfo.getSkinExtractRewardRepeatControl());
                builder.setSkinShowList(paramInfo.getSkinShowList());
                builder.setSkinExtractSpecialParam(paramInfo.getSkinExtractSpecialParam());
                builder.setLotteryType(paramInfo.getLotteryType());
                builder.setInterfaceStyle(paramInfo.getInterfaceStyle());
                builder.setName(ServerLanguageMgr.getContent(paramInfo.getName(), player.getLanguage()));
                builder.setDesc(ServerLanguageMgr.getContent(paramInfo.getDesc(), player.getLanguage()));
                listTemp.addParam(builder);
            }
            syncMsg.addItem(listTemp);
        }
        if(syncMsg.getItemCount() > 0) {
            player.sendPacket(Protocol.U_ACTIVITY_LOTTERY_SYNC_CONFIG, syncMsg);
        }

    }

    public synchronized void initUserData() {
        //初始化跨活动保底数据
        if (guaranteeDataMap == null){
            guaranteeDataMap = new ConcurrentHashMap<>();
        }

        for (Map.Entry<Integer, Map<Integer,ActivityLotteryConfig>> entry : ActivityLotteryMgr.getConfigMap().entrySet()) {
            ActivityLotteryConfig config = entry.getValue().get(0);
            if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
                continue;
            }
            if (config.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue()) {
                if (!SystemOpenMgr.systemOpen(player, eSystemId.PeerlessBeautyLottery.getValue())) {
                    continue;
                }
            }
            if(!userDataMap.containsKey(config.getActivityId())) {
                UserActivityLotteryData userData = new UserActivityLotteryData();
                userData.setActivityId(config.getActivityInfo().getActivityId());
                userData.setLotteryType(0);
                userData.setUserId(player.getUserId());
                userData.setLastDrawTime(System.currentTimeMillis());
                if (guaranteeDataMap.containsKey(config.getActivityType())){
                    UserActivityLotteryGuaranteeData guaranteeData = guaranteeDataMap.get(config.getActivityType());
                    userData.setGetItemMap(new ConcurrentHashMap<>(guaranteeData.getGetItemMap()));
                }

                userData.setInsertOption();
                userDataMap.put(userData.getActivityId(), userData);
            }
            UserActivityLotteryData lotteryData = userDataMap.get(config.getActivityInfo().getActivityId());
            //如果是活动抽奖,并且不是无双美女则需要判断是否有初始化活动通用保底次数
            if (!guaranteeDataMap.containsKey(config.getActivityType()) && config.getActivityInfo().getType() != eActivityType.PeerlessBeautyLotteryActivity.getValue()){
                guaranteeDataMap.put(config.getActivityType(),new UserActivityLotteryGuaranteeData(getUserId(),config.getActivityType(),lotteryData.getTotalDrawTimes(),new ConcurrentHashMap<>(lotteryData.getGetItemMap())));
            }
        }

    }

    public void syncUserData() {

        ActivityLotteryProto.ActivityLotteryDataSyncMsg.Builder syncMsg = ActivityLotteryProto.ActivityLotteryDataSyncMsg.newBuilder();
        for (Map.Entry<Integer, UserActivityLotteryData> entry : userDataMap.entrySet()) {
            UserActivityLotteryData userData = entry.getValue();
            ActivityLotteryConfig config = ActivityLotteryMgr.getActivityLotteryConfig(userData.getActivityId());
            if (null == config){
                continue;
            }
            if(config != null && ActivityMgr.activityOverTime(config.getActivityInfo())){
                continue;
            }
            if (config.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue()) {
                if (!SystemOpenMgr.systemOpen(player, eSystemId.PeerlessBeautyLottery.getValue())) {
                    continue;
                }
            }
            UserActivityLotteryData data = entry.getValue();
            ActivityLotteryProto.ActivityLotteryUserDataTemp.Builder build = ActivityLotteryProto.ActivityLotteryUserDataTemp.newBuilder();
            build.setTotalDrawTimes(data.getTotalDrawTimes());
            build.setActivityId(userData.getActivityId());
            build.setCommonDrawTimes(userData.getCommonDrawTimes());
            build.setNoticeReadTime(userData.getNoticeReadTime());
            build.setSkinId(userData.getLotteryType());
            UserActivityLotteryGuaranteeData guaranteeData = getOrCreateGuaranteeTypeData(config.getActivityType(), userData);
            if(guaranteeData != null){
                build.setGuaranteeDrawTimes(guaranteeData.getDrawCount());
            }
            syncMsg.addGameData(build);
        }

        if(syncMsg.getGameDataCount() > 0) {
            player.sendPacket(Protocol.U_ACTIVITY_LOTTERY_SYNC_USER_DATA, syncMsg);
        }
    }

    public void initSystem() {
        initUserData();
        syncConfig();
        syncUserData();
    }

    //设置皮肤
    public int setSkin(int activityId, int skinId) {
        UserActivityLotteryData userActivityLotteryData = getUserData(activityId);
        if(userActivityLotteryData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        ActivityLotteryConfig config = ActivityLotteryMgr.getActivityLotteryConfig(activityId);
        if(config == null){
            return GameErrorCode.E_ACTIVITY_LOTTERY_SKIN_CONFIG_NOT_FOUND;
        }
        if (config.getSkinChange() == 0 ) {
            // 皮肤限制
            if (userActivityLotteryData.getLotteryType() != 0) {
                return GameErrorCode.E_ACTIVITY_LOTTERY_SKIN_HAD_CHOOSE;
            }
        } else if (config.getSkinChange() == 1) {
            // 皮肤不限制
        }
        if(!config.containsSkinId(skinId)){
            return GameErrorCode.E_ACTIVITY_LOTTERY_SKIN_NOT_FOUND;
        }
        userActivityLotteryData.setLotteryType(skinId);
        player.sendPacket(Protocol.U_ACTIVITY_LOTTERY_SELECT_SKIN, ActivityLotteryProto.ActivityLotterySelectSkinRespMsg.newBuilder().setRet(0));
        syncUserData();
        return 0;
    }
}
